package com.onpositive.data.serializer.writers;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import com.onpositive.data.serializer.readers.DefaultReaderFactory;
import com.onpositive.datamap.values.impl.ScalarRange;

public class RangeWriter extends AbstractWriter<ScalarRange> {

	public RangeWriter() {
		super(ScalarRange.class);
	}

	protected NumericValueCollectionWriter lows = new NumericValueCollectionWriter();
	protected NumericValueCollectionWriter highs = new NumericValueCollectionWriter();
	protected StringWriter strs = new StringWriter();

	@Override
	public void append(ScalarRange value) {
		
		if( value == null ){
			lows.append(null);
			highs.append(null);
			strs.append(null) ;
			return ;
		}	
		
		double low = value.getLowValue();
		double high = value.getHighValue();
		if (low == high) {
			lows.append( null );
			highs.append(high);
		} else {
			lows.append(low);
			highs.append(high);
		}
		Object comment = value.getComment();
		strs.append(comment == null ? null : comment.toString());
	}

	@Override
	protected int getID() {
		return DefaultReaderFactory.RW_ID_RANGE_QUANIFIER;
	}

	@Override
	protected void doSerialize() {
		try {
			ByteArrayOutputStream sm=new ByteArrayOutputStream();
			DataOutputStream stream2 = new DataOutputStream(sm);
			lows.serialize(stream2);
			int s0=stream2.size();
			highs.serialize(stream2);
			int s1=stream2.size();
			strs.serialize(stream2);
			int s2=stream2.size();
			stream2.close();
			stream.writeInt(s0);
			stream.writeInt(s1);
			stream.writeInt(s2);
			stream.write(sm.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
